<?php


namespace app\bock\type\pre;


use app\bock\type\action\CollisionCheck;
use app\bock\type\bock\BockBlack;
use app\bock\type\bock\BockF;
use app\bock\type\bock\BockI;
use app\bock\type\bock\BockL;
use app\bock\type\bock\BockN;
use app\bock\type\bock\BockT;
use app\bock\type\bock\IBock;
use app\bock\type\INode;
use app\bock\type\NodeBackGround;
use app\bock\type\Panel;
use app\bock\type\Point;
use app\bock\type\stack\PanelStack;

class NowBock
{
    /**
     * @var IBock
     */
    protected $bock;

    /**
     * @var Panel
     */
    protected $panel;

    /**
     * @param Panel $panel
     */
    public function setPanel($panel)
    {
        $this->panel = $panel;
    }

    public function __construct()
    {
        $this->createBock();
    }

    public function createBock()
    {
        $defaultPoint = new Point(0,4);

        $bockI = new BockI();
        $bockI->setStartPoint($defaultPoint);

        $bockF = new BockF();
        $bockF->setStartPoint($defaultPoint);

        $bockL = new BockL();
        $bockL->setStartPoint($defaultPoint);

        $bockN = new BockN();
        $bockN->setStartPoint($defaultPoint);

        $bockT = new BockT();
        $bockT->setStartPoint($defaultPoint);

        $bockArray = [
//            $bockF
            $bockI, $bockF, $bockL, $bockN, $bockT
        ];

        $key = array_rand($bockArray);

        $this->bock = $bockArray[$key];
    }

    /**
     * @param IBock $bock
     */
    public function setBock($bock)
    {
        $this->bock = $bock;
    }

    /**
     * @return IBock
     */
    public function getBock()
    {
        return $this->bock;
    }

    public function clearBock()
    {
        $nodes = $this->bock->getAllEffNode();

        foreach ($nodes as $node)
        {
            /**
             * @var INode $node
             */
            $this->panel->setPointNode($node->getPoint(), new NodeBackGround($node->getPoint()));
        }
    }


    /**
     * 重新绘制
     */
    public function renderBock()
    {
        $this->bock->render($this->panel);
    }

    /**
     * 当前方块开始下落
     * @param PanelStack $panelStack
     * @throws \Exception
     */
    public function down(PanelStack $panelStack)
    {
        $oldPoint = $this->bock->getStartPoint();

        // 检测系统
        $check = new CollisionCheck($panelStack, $this->getBock());
        $check->isOver();

        // 碰撞了需要转化为堆, 并且需要重新生成块
        if ($check->check()){

            $panelStack->addStackFromBock($this->getBock());
            $this->createBock();
        }else{
            // 清理之前的痕迹
            $this->clearBock();

            // 渲染新的痕迹
            $newPoint = new Point($oldPoint->getRow() + 1, $oldPoint->getCol());
            $this->bock->setStartPoint($newPoint);

            $this->bock->render($this->panel);
        }
    }
}